package Midium;

import java.util.function.IntConsumer;

//线程题 打印零与奇偶数
public class Solutuin1116 {
    private int n;
    private int count = 1;
    boolean zeroFlag = true;
    boolean evenFlag = false;
    boolean oddFlag = false;

    public Solutuin1116(int n) {
        this.n = n;
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while (!zeroFlag) {
                Thread.yield();
            }
            printNumber.accept(0);
            zeroFlag = false;
            if (count % 2 == 0) {
                evenFlag = true;
            } else {
                oddFlag = true;
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 2 ; i<=n ; i+=2) {
            while (!evenFlag) {
                Thread.yield();
            }
            printNumber.accept(count++);
            zeroFlag = true;
            evenFlag = false;
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1 ; i<=n ; i+=2) {
            while (!oddFlag) {
                Thread.yield();
            }
            printNumber.accept(count++);
            zeroFlag = true;
            oddFlag = false;
        }

    }
}
